<!--
 * @company : 版权所属 四川北星惯牌科技有限公司
 * @contact : 刘经理 19326416371
 -->
<template>

	<view class="competitionStage w100">

		<view class="competition-info">
			<text class="text">比赛情况：当前第{{matchInfo?.current_round}}轮 / 共{{matchInfo?.rounds}}轮</text>
		</view>
		<template v-if="roundInfo.list.length>0">
			<view class="stage-item w100" ref="stageKey" v-for="(item,index) in roundInfo.list" :key="index">
				<!-- 标题 -->
				<view class="stage-item-head">
					<view class="stage-item-head w100 flex-row-center">
						<view class="name-box flex-center">
							<text class="name">{{item.title}}</text>
							<!-- <text class="num">{{num}}</text> -->
						</view>
						<view class="item-center flex-center w100" v-if="item.inner_group">
							<view class="ava-box flex-row-center">
								<!-- 	<view class="ava" v-for="(valTwo,indexTwo) in item.inner_group_left" :key="indexTwo">
									<up-avatar :default-url="errImg" :src="valTwo.avatar" mode="aspectFill"
										size="64rpx"></up-avatar>
								</view> -->
								<up-avatar-group :default-url="errImg" mode="aspectFill" :maxCount="3"
									:urls="item.inner_group_left" size="64rpx" gap="0.4"></up-avatar-group>
							</view>
							<image src="@/page_activity/static/icon_pk.png" class="icon-pk" mode=""></image>
							<view class="ava-box flex-row-center">
								<!-- 	<view class="ava" v-for="(valThree,indexThree) in item.inner_group_right"
									:key="indexThree">
									<up-avatar :default-url="errImg" :src="valThree.avatar" mode="aspectFill"
										size="64rpx"></up-avatar>
								</view> -->
								<up-avatar-group :default-url="errImg" mode="aspectFill" :maxCount="3"
									:urls="item.inner_group_right" size="64rpx" gap="0.4"></up-avatar-group>
							</view>
						</view>
						<view class="item-btn flex-center" @click="changeItemIndex(item,index)">
							<text class="text">详情</text>
							<view :class="[index===itemIndex?'icon-actvie':'icon']">
								<up-icon name="arrow-right-double" color="#DEDEDE" size="28rpx"></up-icon>
							</view>
						</view>
					</view>
				</view>
				<!-- 内容  -->
				<view :animation="index===itemIndex? animationData:animationDataNo"
					:class="[index===itemIndex?'stage-item-content':'content-box','w100']">
					<view class="stage-item-list flex-row-center" v-for="(val,indexGroup) in item.groups"
						:key="indexGroup">
						<view class="flex-row-center">
							<text class="index">{{Number(indexGroup)+1}}</text>
							<view class="user-info flex-row-center">
								<view class="ava">
									<up-avatar :default-url="errImg" :src="val.avatar" mode="aspectFill"
										size="40rpx"></up-avatar>
									<!-- <image src="@/static/logo.png" class="ava" mode="aspectFill"></image> -->
								</view>
								<view class="name-box-user flex-row-center">
									<text class="name">{{val.real_name}}</text>
									<template>
										<up-icon name="account-fill" v-if="val.group_inner_number==1" color="#2979ff"
											size="28rpx"></up-icon>
										<up-icon name="account-fill" v-else color="#f50c6c" size="28rpx"></up-icon>
									</template>
								</view>
							</view>
						</view>
						<view class="stage-item-right flex-row-center">
							<template v-if="alterInfo.id==val.id">
								<up-input type="digit" v-model="alterInfo.score" :customStyle="{
									width: '262rpx',
									height: '68rpx',
									borderRadius: '8rpx',
									border: '2rpx solid #6EC7BE',
									boxSizing: 'border-box',
									padding:'20rpx',
									background:'transparent'
									 }" color="#DEDEDE" @confirm="alterScore" confirmType="done">
									<template #suffix>
										<view class="close-box flex--center" @click="closeEdit">
											<up-icon name="close-circle-fill" color="#4C4C4C" size="34rpx"></up-icon>
										</view>
									</template>
								</up-input>
								<text class="point-text"> 分</text>
							</template>
							<template v-else>
								<text class="point">{{val.score}}分</text>
								<image v-if="matchInfo?.my_scoreWrite_auth==1" @click="changeEditIndex(val,index)"
									src="@/page_activity/static/edit_icon.png" class="edit" mode=""></image>
							</template>

						</view>
					</view>
				</view>
			</view>
		</template>
		<view class="not-list-view" v-else>
			<text class="text">没有进行中得组队~</text>
		</view>
		<view class="competitionStage-btn flex-row-center">
			<!-- 判断是否最后一轮  -->
			<up-button v-if="matchInfo?.my_matchEnd_auth==1" text="结束比赛" :loading="btnInfo.endLoading" shape="circle"
				loadingText="正在提交" @click="roundEnd" :customStyle="{
						width:'300rpx',
					height:'88rpx',
					fontWeight: 'bold',
					fontSize: '34rpx',
					color: '#0A534F',
				}" color="linear-gradient( 270deg, #94DEAC 0%, #7CDEC7 47%, #79DED3 100%)"></up-button>
			<template v-if="matchInfo?.my_roundStart_auth==1&&matchInfo?.isLastRound!=1">
				<up-button text="进行下一轮" :loading="btnInfo.startLoading" shape="circle" loadingText="正在切换"
					@click="roundStart" :customStyle="{
				height:'88rpx',
				width:'320rpx',
				fontWeight: 'bold',
				fontSize: '34rpx',
				color: '#0A534F',
			}" color="linear-gradient( 270deg, #94DEAC 0%, #7CDEC7 47%, #79DED3 100%)"></up-button>
			</template>
		</view>
	</view>
	<!-- #ifdef MP-WEIXIN -->
	<root-portal>
	<!-- #endif -->
		<!-- 	<up-modal showCancelButton title="提示" @cancel="canselRoundBtn" content="进入下一轮，确定当前轮次已完成?" cancelText="取消"
			:show="btnInfo.show" :confirmColor="btnInfo.color" :confirmText="btnInfo.text" @confirm="confirmStart"
			ref="uModal" :asyncClose="false"></up-modal> -->
		<up-modal :show="alterInfo.show" confirmColor="#7EDE9E" showCancelButton title="修改积分" @confirm="alterScore"
			@cancel="closeEdit">
			<view class="slot-content">
				<up-input type="number" v-model="alterInfo.score" :customStyle="{
						width: '362rpx',
						height: '68rpx',
						borderRadius: '8rpx',
						boxSizing: 'border-box',
						padding:'20rpx',
						border:'1rpx solid #191C1F'
						 }" color="#191C1F" @confirm="alterScore" confirmType="done">
				</up-input>
			</view>
		</up-modal>
	<!-- #ifdef MP-WEIXIN -->
	</root-portal>
	<!-- #endif -->
</template>

<script setup>
	import {
		configInfoStore
	} from '@/stores/config.js';
	const emit = defineEmits(['changeStage']);
	const {
		configInfo
	} = configInfoStore();
	const errImg = ref(computed(() => configInfo.user_default_avatar?.value));
	const stageKey = ref(null);
	import {
		matchInfoStore
	} from '@/stores/match';
	const matchStore = matchInfoStore();
	const matchInfo = computed(() => matchStore.matchInfo);
	const itemIndex = ref(null);
	const alterInfo = reactive({ //编辑对象
		score: 0,
		index: null,
		show: false,
		id: 0
	})
	const animationData = ref('');
	const animationDataNo = ref('');
	const btnInfo = reactive({
		text: '',
		timer: null,
		color: "#ccc",
		show: false,
		endLoading: false,
		startLoading: false
	})
	const roundInfo = reactive({
		list: []
	})
	onMounted(() => {
		getMatchRound();
		const animation = uni.createAnimation({
			duration: 300,
		});
		animation.height(0).step();
		animationDataNo.value = animation.export();
	});
	onPullDownRefresh(() => {
		console.log('比赛轮次得组件刷新了');
		if (matchInfo.value?.stepsIndex == 1) {
			roundInfo.list = [];
			getMatchRound();
		}
	});
	const confirm = () => {};
	const getMatchRound = async (id) => {
		const res = await $Api.match.getMatchRound({
			match_id: matchInfo.value?.m_id
		}, true);
		if (res.code === 1) {
			if (res.data && res.data.length > 0) {
				let arr = [];
				arr = res.data.map(val => {
					let inner_group_left = [];
					let inner_group_right = [];
					if (val.inner_group) {
						if (val.inner_group['1'] && val.inner_group['1'].length > 0) {
							val.inner_group['1'].forEach(item => {
								inner_group_left.push(item.avatar);
							})
						}
						if (val.inner_group['2'] && val.inner_group['2'].length > 0) {
							val.inner_group['2'].forEach(item => {
								inner_group_right.push(item.avatar)
							})
						}
					}
					return {
						...val,
						inner_group_left,
						inner_group_right
					}
				})
				roundInfo.list = arr;
				console.log('roundInfo.list', roundInfo.list);
			}
		} else {
			uni.$u.toast(res.msg);
		}
	}
	const roundStart = () => { //切换下一轮
		uni.showModal({
			title: '提示',
			content: '进入下一轮，确定当前轮次已完成?',
			success: (res) => {
				if (res.confirm) {
					startMatch();
				} else if (res.cancel) {
					console.log('用户点击取消');
				}
			}
		});

	};
	const roundStartTwo = () => {
		if (btnInfo.timer) return;
		btnInfo.show = true;
		let int = 5;
		btnInfo.text = '确定（5s)'
		btnInfo.timer = setInterval(() => {
			int--;
			btnInfo.text = `确定（${int}s）`;
			if (int <= 0) {
				clearInterval(btnInfo.timer);
				btnInfo.timer = null;
				btnInfo.text = '确定';
				btnInfo.color = "#66DEC2"
			}
		}, 1000)
	};
	const confirmStart = () => {
		if (btnInfo.timer) return;
		startMatch();
	};
	const canselRoundBtn = () => { //取消按钮
		clearInterval(btnInfo.timer);
		btnInfo.timer = null;
		btnInfo.text = '确定（5s)';
		btnInfo.color = "#ccc";
		btnInfo.show = false;
	}
	const roundEnd = () => {
		uni.showModal({
			title: '提示',
			content: '请确保所有轮次已完成，再结束比赛？',
			success: (res) => {
				if (res.confirm) {
					endMatch();
				} else if (res.cancel) {
					console.log('用户点击取消');
				}
			}
		});
	};
	const startMatch = async () => { //进入下一轮
		if (btnInfo.startLoading) return;
		btnInfo.startLoading = true;
		const res = await $Api.match.startMatch({
			match_id: matchInfo.value.m_id,
			next: 'TURN_ON'
		}, true);
		if (res.code === 1) {
			uni.showToast({
				title: '提交成功！'
			})
			setTimeout(() => {
				btnInfo.startLoading = false;
				roundInfo.list = [];
				matchInfo.value.current_round++; //状态
				if (matchInfo.value.current_round >= matchInfo.value.rounds) { //判断是否最后一场
					matchInfo.value.isLastRound = 1;
				}
				getMatchRound();
			}, 300)
		} else {
			btnInfo.startLoading = false;
			uni.$u.toast(res.msg);
		}
	};
	const endMatch = async () => {
		if (btnInfo.endLoading) return;
		btnInfo.endLoading = true;
		const res = await $Api.match.matchEnd({
			match_id: matchInfo.value.m_id,
		}, true)
		if (res.code == 1) {
			uni.showToast({
				title: '提交成功！'
			});
			setTimeout(() => {
				emit('changeStage', 2); //切换状态
				btnInfo.endLoading = false;
			}, 400)
		} else {
			btnInfo.endLoading = false;
			uni.$u.toast(res.msg);
		}
	}
	const alterScore = async () => { //修改分数
		const res = await $Api.match.alterPoint({
			match_id: matchInfo.value.m_id,
			id: alterInfo.id,
			// score: Number(alterInfo.score)
			score: parseInt(alterInfo.score)
		}, true)
		if (res.code == 1) {
			setTimeout(() => {
				uni.showToast({
					title: '录入成功'
				});
				setTimeout(() => {
					if (roundInfo.list[alterInfo.index]?.groups && roundInfo.list[alterInfo.index]
						.groups.length > 0) {
						roundInfo.list[alterInfo.index].groups = roundInfo.list[alterInfo.index]
							.groups
							.map(val => {
								if (alterInfo.id == val.id) {
									val.score = parseInt(alterInfo.score)
								}
								return val
							})
					}

					// roundInfo.list = roundInfo.list.map(item => {
					// 	let group = [];
					// 	group = item.groups.map(val => {
					// 		if (alterInfo.id == val.id) {
					// 			val.score = parseInt(alterInfo.score)
					// 		}
					// 		return val
					// 	})
					// 	return {
					// 		...item,
					// 		groups:group
					// 	}
					// })
					closeEdit();
					// getMatchRound();
				}, 300)
			}, 300)
		} else {
			uni.$u.toast(res.msg);
		}
	}
	const changeItemIndex = async (item, index) => { //查看详情
		const animation = uni.createAnimation({
			duration: 300,
		});
		closeEdit(); //取消编辑
		if (itemIndex.value === index) { //收起详情
			itemIndex.value = null;
			await nextTick();
			animation.height(0).step();
			animationData.value = animation.export();
			return
		}
		// console.log('animationDataNo.value', animationDataNo.value);
		itemIndex.value = index;
		await nextTick();
		let height = item.groups.length ? (item.groups.length * 50) + 'px' : '200px';
		animation.height(height).step();
		animationData.value = animation.export();
	}
	const changeEditIndex = (item, index) => { //切换编辑对象
		alterInfo.show = true; //关闭键盘
		alterInfo.id = item.id;
		alterInfo.index = index;
		if (item.score <= 0) {
			alterInfo.score = 0;
			return;
		}
		alterInfo.score = parseInt(item.score);
	}
	const closeEdit = () => { //取消编辑
		alterInfo.show = false; //关闭键盘
		alterInfo.score = 0;
		alterInfo.id = 0;
		alterInfo.index = null;
	}
	const confirmPoint = (valId) => { //完成修改积分
		console.log('修改人员id', valId);
	}
</script>
<style>
	.u-input,
	.u-textarea {
		padding: 0 !important;
		background-color: transparent !important;
	}

	.placeholderClass {
		color: #5B6868 !important;
		font-size: 26rpx;
		font-weight: 500;
	}
</style>
<style lang="scss" scoped>
	.competitionStage {
		transform: none;

		.competition-info {
			margin-bottom: 24rpx;

			.text {
				font-size: 30rpx;
				color: $name-color;
			}
		}
	}

	.stage-item {
		width: 100%;
		border-radius: 24rpx;
		border: 2rpx solid #69BBB0;
		margin-bottom: 24rpx;

		.stage-item-head {
			justify-content: space-between;
		}

		.name-box {
			width: 130rpx;
			color: $title-color;
			flex-shrink: 0;
			height: 118rpx;

			.name {
				font-size: 24rpx;
			}

			.num {
				font-size: 32rpx;
				font-weight: bold;
				margin: 0 4rpx;
			}
		}

		.item-center {
			flex: 1;
			border-left: 2rpx solid #3E6663;
			height: 100%;
			border-right: 2rpx solid #3E6663;
			height: 118rpx;

			.ava-box {
				width: 142rpx;
				justify-content: space-between;

				.ava {
					border-radius: 50%;
					width: 64rpx;
					height: 64rpx;
					overflow: hidden;
				}
			}

			.ml-16 {
				margin-left: 16rpx;
			}

			.mr-16 {
				margin-left: 16rpx;
			}

			.icon-pk {
				width: 48rpx;
				height: 48rpx;
				margin: 0 28rpx;
			}
		}

		.item-btn {
			width: 118rpx;
			font-weight: 500;
			font-size: 24rpx;
			color: $title-color;
			flex-shrink: 0;
			height: 118rpx;

			.text {
				margin-right: 10rpx;
			}

			.icon {
				transition: all .5s;
				transform: rotate(90deg);
			}

			.icon-actvie {
				transition: all .5s;
				transform: rotate(-90deg);
			}
		}
	}

	.content-box {
		height: 0;
		overflow: hidden;
		padding: 0rpx 32rpx;

	}

	.stage-item-content {
		// padding: 42rpx 32rpx;
		// height: 0;
		overflow: hidden;
		padding: 0rpx 32rpx;
		border-top: 2rpx solid #2C4343;
		// height: 400rpx;
		// height: auto;
		// transition: height .5s;
	}

	.stage-item-list {
		justify-content: space-between;
		// border: 1rpx solid red;
		// height: 100rpx;
		height: 50px;

		.stage-item-right {
			flex-shrink: 1;
		}

		&:not(:last-child) {}

		.index {
			font-family: YouSheBiaoTiHei;
			font-weight: 400;
			font-size: 30rpx;
			color: #79DED3;
			text-align: center;
		}

		.user-info {
			margin-left: 42rpx;

			.ava {
				border-radius: 50%;
				width: 40rpx;
				height: 40rpx;
				overflow: hidden;
			}

			.name-box-user {
				margin-left: 16rpx;

				.name {
					font-weight: 500;
					font-size: 28rpx;
					color: $name-color;
					margin-right: 12rpx;
					max-width: 180rpx;
					text-overflow: ellipsis;
					white-space: nowrap;
					lines: 1;
					overflow: hidden;
				}
			}


		}

		.close-box {
			width: 42rpx;
			height: 100%;
			border-radius: 50%;
		}

		.point {
			font-weight: 400;
			font-size: 28rpx;
			color: $name-color;
		}

		.int-box {
			width: 262rpx;
			height: 68rpx;
			border-radius: 8rpx;
			border: 2rpx solid #6EC7BE;
			box-sizing: border-box;
			padding: 20rpx;
			color: #fff !important;
		}

		.point-text {
			font-weight: 400;
			font-size: 28rpx;
			color: $name-color;
			margin-left: 8rpx;
		}

		.edit {
			width: 44rpx;
			height: 44rpx;
			margin-left: 60rpx;
		}
	}

	.competitionStage-btn {
		margin-top: 72rpx;
	}
</style>